from openpyxl import load_workbook

from django.http import HttpResponse, JsonResponse
from django.core.serializers import serialize
from django.core.cache import cache

from ...models.users import Users, UsersGroup
from ...models.configs import Configs
from ...models.chat_model import ChatModel

from ...utils.data_handle import is_mobile_number, generate_popular_chinese_nickname, paginate
from ...utils.users import generate_salt
from ...utils.time_conversion import datetime_to_times

import json


def importusers(request):
    '''
    导入用户
    上传execl表格文件，批量创建用户
    '''
    get_params = request.GET.dict()

    if request.method == 'POST':
        # 获取当前登陆的admin 用户
        adminuserid = request.session.get('LOGIN_USER_ID_ADMIN', None)
        if adminuserid is None:
            res_mes = {
                "code": 1,
                "message": "请登陆!"
            }
            res_mes_json = json.dumps(res_mes, ensure_ascii=False)
            return HttpResponse(res_mes_json)

        if request.FILES:
            data = []  # 存储所有工作表的数据
            try:
                excel_file = request.FILES['excel_file']  # 获取上传的Excel文件
                # excel_file_name = excel_file.name

                workbook = load_workbook(excel_file, data_only=True)

                sheet = workbook.active

                # # 读取表头
                headers = [cell.value for cell in sheet[1]]

                # 读取表数据
                rows = []
                for row in sheet.iter_rows(min_row=2, values_only=True):
                    rows.append(row)
                
                # 打印表头和表数据
                # print("Headers:", headers)
                # data = []  # 存储所有工作表的数据
                '''
                [{'username': 123456789, 'nickname': '测试1', 'power': 100, 'expired_time': datetime.datetime(2024, 9, 9, 0, 0), 'chat_models_json': 'gpt-4o,gpt-4', 'usergroup': 'nsd1512'}, 
                 {'username': 987654321, 'nickname': '测试2', 'power': 200, 'expired_time': datetime.datetime(2024, 10, 12, 0, 0), 'chat_models_json': 'gpt-4', 'usergroup': 'nsd1512'}]
                '''
                for row in rows:
                    if row:
                        if row[0] is not None or row[0]:
                            # print(row, "aaa")
                            zip_data = dict(zip(headers, row))
                            data.append(zip_data)
                            # print(f"Row {i+1}:", dict(zip(headers, row)))
                
            except:
                res_mes = {
                    "code": 1,
                    "message": "请上传正确的表格文件!"
                }
                res_mes_json = json.dumps(res_mes, ensure_ascii=False)
                return HttpResponse(res_mes_json)
            
            # print(data)
            
            if not data:
                res_mes = {
                    "code": 1,
                    "message": "没有读取到表格文件!"
                }
                res_mes_json = json.dumps(res_mes, ensure_ascii=False)
                return HttpResponse(res_mes_json)
            else:
                # {'username': 123456789, 'nickname': '测试1', 'power': 100, 'expired_time': datetime.datetime(2024, 9, 9, 0, 0), 'chat_models_json': 'gpt-4o,gpt-4', 'usergroup': 'nsd1512'}
                # 先实力话一个用户obj
                chat_config_json = Configs.objects.get(marker="system").config_json

                # 保存用户信息
                for index, usermes in enumerate(data):
                    chatusers_instance = Users()
                    isuser = True
                    usermes['iserror'] = False
                    usermes['errormes'] = ""
                    # 判断用户手机号 唯一 *******
                    if "username" in usermes:
                        if is_mobile_number(usermes['username']):
                            getuser = Users.objects.filter(username=usermes['username'])
                            if getuser:
                                isuser = False
                                usermes['iserror'] = True
                                usermes['errormes'] += "此用户已存在,"
                            else:
                                chatusers_instance.username = usermes['username']
                        else:
                            isuser = False
                            usermes['iserror'] = True
                            usermes['errormes'] += "用户名不是有效手机号,"
                    else:
                        isuser = False
                        usermes['iserror'] = True
                        usermes['errormes'] += "没有用户名,"

                    # 昵称
                    if "nickname" in usermes:
                        if usermes['nickname']:
                            chatusers_instance.nickname = usermes['nickname']
                        else:
                            nickname = generate_popular_chinese_nickname()
                            chatusers_instance.nickname = nickname
                            usermes['nickname'] = nickname
                    else:
                        nickname = generate_popular_chinese_nickname()
                        chatusers_instance.nickname = nickname
                        usermes['nickname'] = nickname

                    # 算力
                    if "power" in usermes:
                        if usermes['power']:
                            chatusers_instance.power = usermes['power']
                        else:
                            # 如果没有设置算力的话 就获取系统设置的注册用户得到的算力
                            default_power = chat_config_json['init_power']
                            chatusers_instance.power = default_power

                            usermes['power'] = default_power
                    else:
                        # 如果没有设置算力的话 就获取系统设置的注册用户得到的算力
                        default_power = chat_config_json['init_power']
                        chatusers_instance.power = default_power

                        usermes['power'] = default_power

                    # 用户过期时间
                    if "expired_time" in usermes:
                        if usermes['expired_time']:
                            chatusers_instance.expired_time = usermes['expired_time']
                            usermes['expired_time'] = datetime_to_times(usermes['expired_time'])
                        else:
                            # 如果没有设置的话 那就设置成永久用户
                            chatusers_instance.expired_time = None
                            usermes['expired_time'] = ""
                    else:
                        # 如果没有设置的话 那就设置成永久用户
                        chatusers_instance.expired_time = None
                        usermes['expired_time'] = ""

                    # 默认模型
                    if "chat_models_json" in usermes:
                        if usermes['chat_models_json']:
                            models_str = usermes['chat_models_json']
                            models_list = models_str.split(',')
                            models_id_list = list(ChatModel.objects.filter(value__in=models_list).values_list('id',  flat=True))
                            chatusers_instance.chat_models_json = models_id_list
                        else:
                            default_models = chat_config_json['default_models']
                            chatusers_instance.chat_models_json = default_models

                            usermes['chat_models_json'] = "系统设置的默认模型"
                    else:
                        default_models = chat_config_json['default_models']
                        chatusers_instance.chat_models_json = default_models

                        usermes['chat_models_json'] = "系统设置的默认模型"

                    chatusers_instance.password = "导入用户，没有密码"
                    chatusers_instance.avatar = "/images/avatar/user.png"
                    chatusers_instance.salt = generate_salt(8)
                    chatusers_instance.chat_roles_json = ["gpt"]
                    
                    # 保存用户
                    try:
                        if isuser:
                            chatusers_instance.save()

                            # 保存关联用户组
                            # 因为只有等到用户创建成功了 之后才能关联用户组
                            usergroup_str = usermes['usergroup']
                            if usergroup_str:
                                usergroup_list = usergroup_str.split(',')
                                all_usergroup_obj_list = list(UsersGroup.objects.filter(groupname__in=usergroup_list))
                                user_obj = Users.objects.get(username=usermes['username'])

                                user_obj.userList.add(*all_usergroup_obj_list)
                        else:
                            pass

                        usermes['id'] = index

                    except Exception as e:
                        usermes['iserror'] = True
                        usermes['errormes'] += e

                # 把上传的用户信息列表 保存在redis里。临时数据
                cache.set("importusers-file-{}".format(adminuserid), data, timeout=300)    # 缓存5分钟

                # 给一个列表分页，返回数据
                usermes_list = paginate(data, get_params['page'], get_params['page_size'])

                res_mes = {
                    "code": 0,
                    "data": usermes_list
                }
                res_mes_json = json.dumps(res_mes, ensure_ascii=False)
                return HttpResponse(res_mes_json)


    # GET 请求
    else:
        # 获取当前登陆的admin 用户
        adminuserid = request.session.get('LOGIN_USER_ID_ADMIN', None)
        if adminuserid is None:
            res_mes = {
                "code": 1,
                "message": "请登陆!"
            }
            res_mes_json = json.dumps(res_mes, ensure_ascii=False)
            return HttpResponse(res_mes_json)
        
        # 获取导入缓存
        data = cache.get("importusers-file-{}".format(adminuserid))    # 缓存5分钟

        if data:
            # 给一个列表分页，返回数据
            usermes_list = paginate(data, get_params['page'], get_params['page_size'])
        else:
            usermes_list = {
                "items": [],
                "page": get_params['page'],
                "page_size": get_params['page_size'],
                "total": 0,
                "total_page": 0
            }


        res_mes = {
            "code": 0,
            "data": usermes_list
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)

